<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Trans\Common\CancelService;
use JLPay\Models\Trans\Common\CancelRequest;
use JLPay\Models\Trans\Common\CancelResponse;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 交易 - Common撤销功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建撤销请求
 */
function buildCancelRequest(): CancelRequest
{
    $request = new CancelRequest();
    
    // 设置请求参数
    $request->setMchId("849584358120018");
    $request->setOutTradeNo("ld" . date("YmdHis") . rand(1000, 9999));
    $request->setOriOutTradeNo("ld201911023465529");
    $request->setTotalFee("100");
    $request->setOriTransactionId("123456789012345678");
    $request->setRemark("撤销测试");
    $request->setMchCreateIp("123.12.12.123");
    $request->setLongitude("116.078631");
    $request->setLatitude("39.71274");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 撤销示例
 */
function cancelDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行撤销示例");
    
    // 创建配置对象和撤销服务
    $config = createConfig();
    $cancelService = new CancelService($config);
    
    // 创建撤销请求
    $request = buildCancelRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $cancelService, 
        $request, 
        "撤销",
        function($service, $request) {
            return $service->cancel($request);
        }
    );
    
    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    
    $logger->info("撤销示例执行完毕");
}

// =================== 主程序 =====================
$logger = Logger::getInstance();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 撤销示例 开始 =====");
$logger->info("=" . str_repeat("=", 50));

cancelDemo();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 撤销示例执行完毕 =====");
$logger->info("=" . str_repeat("=", 50)); 